﻿using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;


namespace SQLServerHelper
{
    /// <summary>
    ///DBMessageLog 的摘要说明
    /// </summary>
    public class SQLExceptionLog
    {

        static string strConnerction = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        static readonly string strInsertSql = "INSERT INTO [SqlExceptionLog](SqlText,ErrorMsg,CurrentURL) values(@sqlText,@errMsg,@CurrentUrl)";


        private bool IsRecordLog
        {
            get
            {
                bool isTrue = false;
                var isExexts = System.Configuration.ConfigurationManager.AppSettings["IsSqlExceptionLog"];
                if (isExexts != null && isExexts.ToString() == "1")
                {
                    isTrue = true;
                }
                return isTrue;
            }
        }

        public SQLExceptionLog()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        SqlConnection GetConnection()
        {
            return new SqlConnection(strConnerction);
        }

        string CurrentUrl
        {
            get
            {
                string url = "";
                if (HttpContext.Current != null)
                {
                    url = HttpContext.Current.Request.Url != null ? HttpContext.Current.Request.Url.AbsoluteUri : "";
                }
                return url;
            }
        }


        /// <summary>
        /// 异常信息
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="strCatch"></param>
        public void AddThrowErrorbLog(string sql, string strErrMsg, string type)
        {
            if (!IsRecordLog)
                return;

            SqlConnection conn = GetConnection();
            try
            {
                System.Text.StringBuilder sbSql = new System.Text.StringBuilder();
                sbSql.Append(strInsertSql);

                SqlParameter[] parameters = new SqlParameter[] { 
                new SqlParameter("@sqlText",GetSqlType(type)+sql),
                 new SqlParameter("@errMsg",strErrMsg),
                 new SqlParameter("@CurrentUrl",CurrentUrl)
                
            };

                SqlCommand cmd = new SqlCommand(sbSql.ToString(), conn);
                cmd.Parameters.AddRange(parameters);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
        }
        /// <summary>
        /// 异常信息
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="strCatch"></param>
        public void AddThrowErrorbLog(string sql, string type, System.Data.SqlClient.SqlParameter[] parameters, string strErrMsg)
        {
            if (!IsRecordLog)
                return;

            SqlConnection conn = GetConnection();

            try
            {
                System.Text.StringBuilder sbSql = new System.Text.StringBuilder();

                sbSql.Append(strInsertSql);
                System.Text.StringBuilder sbMsg = new System.Text.StringBuilder();
                string strType = GetSqlType(sql);
                if (string.IsNullOrEmpty(strType))//普通语句
                {

                    foreach (SqlParameter item in parameters)
                    {
                        if (item.SqlDbType == SqlDbType.VarChar || item.SqlDbType == SqlDbType.NVarChar)
                            sql = sql.Replace(item.ParameterName, "'" + item.Value.ToString().Replace("'", "\"") + "'");
                        else
                            sql = sql.Replace(item.ParameterName, item.Value.ToString());
                    }
                }
                else
                {
                    foreach (SqlParameter item in parameters)//存储过程
                    {
                        if (item.SqlDbType == SqlDbType.VarChar || item.SqlDbType == SqlDbType.NVarChar)
                            sbMsg.Append(" " + item.ParameterName + "='" + item.Value.ToString().Replace("'", "\"") + "',");
                        else
                            sbMsg.Append(" " + item.ParameterName + "=" + item.Value + ",");
                    }
                }
                SqlParameter[] param = new SqlParameter[] { 
                new SqlParameter("@sqlText",strType+sql+" "+sbMsg.ToString().TrimEnd(',')),
                 new SqlParameter("@errMsg",strErrMsg),
                  new SqlParameter("@CurrentUrl",CurrentUrl)
            };

                SqlCommand cmd = new SqlCommand(sbSql.ToString(), conn);
                cmd.Parameters.AddRange(param);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
        }

        string GetSqlType(string type)
        {
            string result = "";
            if (type == "proc")
                result = "exec ";
            return result;
        }
    }
}